<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { InterviewQuestion } from '#/api/interview/question/model';

import { useAccess } from '@vben/access';
import { Page, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import { Modal, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  delQuestion,
  getQuestionList,
  updateAllQuestionDifficulty,
} from '#/api/interview/question';
import { TableSwitch } from '#/components/table';

import { columns, querySchema } from './data';
import QuestionModal from './question-modal.vue';
import AiQuestionModal from './ai-question-modal.vue';
import { onMounted, ref } from 'vue';
import { getCategoryList } from '#/api/interview/category';
import { listToTree, addFullName } from '@vben/utils';

// 分类数据
const categoryTreeData = ref<any[]>([]);

// 表单配置
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

// 表格配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await getQuestionList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          delFlag: '0',
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'questionId',
  },
  toolbarConfig: {
    refresh: true,
    custom: true,
  },
  id: 'interview-question-index',
};

// 加载分类数据
async function setupCategorySelect() {
  try {
    const res = await getCategoryList({ status: '0' });
    // 转换为树形结构
    const treeData = listToTree(res.rows, {
      id: 'categoryId',
      pid: 'parentId',
      children: 'children',
    });
    // 添加全名，显示层级关系
    addFullName(treeData, 'categoryName', ' / ');
    categoryTreeData.value = treeData;

    // 更新表单中分类选择框的数据
    tableApi.formApi?.updateSchema([
      {
        componentProps: {
          treeData,
        },
        fieldName: 'categoryId',
      },
    ]);
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
}

// 组件挂载时加载分类数据
onMounted(async () => {
  await setupCategorySelect();
});

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [QuestionModalComp, modalApi] = useVbenModal({
  connectedComponent: QuestionModal,
});

// AI生成面试题模态框
const [AiQuestionModalComp, aiQuestionModalApi] = useVbenModal({
  connectedComponent: AiQuestionModal,
});

function handleAdd() {
  modalApi.setData({ update: false });
  modalApi.open();
}

// AI生成面试题
function handleAiGenerate() {
  aiQuestionModalApi.open();
}

async function handleEdit(record: InterviewQuestion) {
  modalApi.setData({ id: record.questionId, update: true });
  modalApi.open();
}

async function handleDelete(row: InterviewQuestion) {
  await delQuestion(row.questionId);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: InterviewQuestion) => row.questionId);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await delQuestion(ids.join(','));
      await tableApi.query();
    },
  });
}

// 更新所有面试题难度
async function handleUpdateAllDifficulty() {
  Modal.confirm({
    title: '提示',
    content: '确认更新所有面试题的难度吗？',
    onOk: async () => {
      await updateAllQuestionDifficulty();
      await tableApi.query();
    },
  });
}

const { hasAccessByCodes } = useAccess();

// 状态切换
async function handleChangeStatus(record: InterviewQuestion) {
  // 这里应该调用API更新状态，但目前未实现
  console.warn('状态切换功能尚未完全实现', record);
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="面试题列表">
      <template #toolbar-tools>
        <Space>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['interview:question:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['interview:question:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['interview:question:add']"
            @click="handleAiGenerate"
          >
            AI生成
          </a-button>
          <a-button
            type="primary"
            v-access:code="['interview:question:edit']"
            @click="handleUpdateAllDifficulty"
          >
            更新难度
          </a-button>
        </Space>
      </template>
      <template #status="{ row }">
        <TableSwitch
          v-model="row.status"
          :api="() => handleChangeStatus(row)"
          :disabled="!hasAccessByCodes(['interview:question:edit'])"
          :reload="() => tableApi.query()"
        />
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['interview:question:edit']"
            @click.stop="handleEdit(row)"
          >
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['interview:question:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <QuestionModalComp @reload="tableApi.query()" />
    <AiQuestionModalComp @reload="tableApi.query()" />
  </Page>
</template>